require 'rubygems'
require 'iconv'
require 'htmlentities'
require 'hpricot'
require 'open-uri'
IRCBot::Plugin.define 'faidqdb' do
	help_string 'Gets a FaiDqdb quote. Use with no params or "latest" to get the latest quote.'
	
	def command(user,target,message,hostmask)
		command = message.split[0]
		message = message.sub(command,'').strip if command
		if command == 'latest' or !command then
			doc = Hpricot(open('http://faidqdb.niexs.net/'))
			number = doc.search('a')[2]['name'].to_i
			text = Iconv.conv('ISO-8859-1','utf-8',HTMLEntities.new.decode(doc.at('p').inner_html.gsub("<br />\r\n",' / ').gsub("\t",'')))
			if text.split(' / ').count >=5 then
				privmsg(target,"Quote is far too long for IRC display. Link: http://faidqdb.niexs.net/quotes/#{number}")
			else
				privmsg(target,"Quote ##{number}: #{text}")
			end
		else
			doc = Hpricot(open("http://faidqdb.niexs.net/quotes/#{command}"))
			number = command.to_i
			text = Iconv.conv('ISO-8859-1','utf-8',HTMLEntities.new.decode(doc.at('p').inner_html.gsub("<br />\r\n",' / ').gsub("\t",'')))
			if text.split(' / ').count >=5 then
				privmsg(target,"Quote is far too long for IRC display. Link: http://faidqdb.niexs.net/quotes/#{number}")
			elsif text.strip.empty? then
				privmsg(target,"That quote doesn't exist!")
			else
				privmsg(target,"Quote ##{number}: #{text}")
			end
		end
	end
end
